<?php

namespace App\Listeners;

use App\Events\sendSubjectEcent;
use App\Models\Episode;
use App\Models\Trace;
use App\Models\User;
use App\Models\Video;
use App\Services\wxService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;

class SendSubListener implements ShouldQueue
{
//    public $connection = 'database';
    /**
     * 任务将被发送到的队列的名称。
     *
     * @var string|null
     */
    public $queue = 'sendSub';
    /**
     * 任务被处理的延迟时间（秒）。
     *
     * @var int
     */
    public $delay = 0;
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * 1 查询订阅该剧的用户
     * 2 向用户发送订阅消息
     * @param  \App\Events\sendSubjectEcent  $event
     * @return void
     */
    public function handle(sendSubjectEcent $event)
    {
        $tlist=Trace::where('episodes_id',$event->episodes_id)->get()->toArray();
        $users=Arr::pluck($tlist,'user_id');
        collect($users)->each(function ($user_id,$key) use ($event){
                $user=User::find($user_id);
                $episodes=Episode::find($event->episodes_id);
                $video=Video::find($event->video_id);
                $data=[
                    'thing1'=>$episodes->name,
                    'time2'=>$video->created_at,
                    'thing3'=>'第'.$video->sort.'集',
                    'thing4'=>'好剧不断，速来观看'];
                 $wxserver=new wxService('miniapp',$user->mps_id);
                $res=$wxserver->sendSubscribe($user->wx_openid,$event->template_id,$data);
                $res=json_decode($res,true);
                if($res['errcode']!=0){
                    dump('发送消息失败,错误码:'.$res['errcode'].'错误描述:'.$res['errmsg']);
                }
        });
        $video=Video::find($event->video_id);
        $video->sendsub=1;
        $video->save();
    }
    public function failed(sendSubjectEcent $event, \Throwable $e)
    {
        Log::info($this->queue.'队列报错了',[$e->getMessage(),$e->getLine(),$e->getFile()]);
    }
}
